package se.webbzon.oschi01.aes;

import java.io.IOException;
import java.io.OutputStream;

public class HexOutputStream extends OutputStream {
	
	// The underlying output stream
	private final OutputStream os;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public HexOutputStream(OutputStream os) {
		this.os = os;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Converts the provided byte array to a string of hexadecimal 
	 * characters. **/
	public static String toHex(byte[] bytes) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			byte b = bytes[i];
			builder.append((char) toUTF8Hex((b >> 4) & 0x0000000F));
			builder.append((char) toUTF8Hex(b & 0x0000000F));
		}
		return builder.toString();
	}

	@Override public void write(int b) throws IOException {
		os.write(toUTF8Hex((b >> 4) & 0x0000000F));
		os.write(toUTF8Hex(b & 0x0000000F));
	}
	
	@Override public void flush() throws IOException {
		os.flush();
	}
	
	@Override public void close() throws IOException {
		os.close();
	}
	
	/*============================================================
	Private Methods
	============================================================*/
	
	/** Returns the byte code of the hexadecimal UTF-8 character
	 * representing the given value. **/
	private static final byte toUTF8Hex(int i) {
		if (i > 9)
			return  (byte) (i + 87);
		else
			return (byte) (i + 48);
	}

}
